package com.mmlc.meimei.lichengkongjian.shoppingbag;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.content.CursorLoader;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.mine.ActivityContacts;
import com.mmlc.meimei.lichengkongjian.mine.ActivityCustomerChoice;
import com.mmlc.network.filter.PromoteRequestFilter;
import com.mmlc.network.responsebean.PromoteSucessResponseBean;
import com.mmlc.utils.ToastUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/29.
 */
public class PromoteActivity extends InterActivity implements View.OnClickListener {

    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.rl_title)
    RelativeLayout rlTitle;
    @InjectView(R.id.edt_name)
    EditText edtName;
    @InjectView(R.id.edt_phone)
    EditText edtPhone;
    @InjectView(R.id.edt_reason)
    EditText edtReason;
    @InjectView(R.id.ib_getcustomer)
    ImageButton ibGetcustomer;
    @InjectView(R.id.ib_contacts)
    ImageButton ibContacts;
    @InjectView(R.id.tv_save)
    TextView tvSave;

    @Override
    protected int initContentView() {
        return R.layout.activity_promote;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);

        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString("客户姓名");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14,true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        edtName.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

        ss = new SpannableString("手机号码");
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        edtPhone.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

        ss = new SpannableString("在此描述详细问题");
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        edtReason.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失

    }

    public static int REQUEST_CODE = 100;
    @OnClick({R.id.iv_back,R.id.ib_getcustomer,R.id.ib_contacts,R.id.tv_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ib_getcustomer:
                Intent intent = new Intent(this, ActivityCustomerChoice.class);
                startActivityForResult(intent,REQUEST_CODE);
                break;
            case R.id.ib_contacts:
                chooseContact();
                break;
            case R.id.tv_save:
                submit();
                break;
        }

    }

    public String name,phone,reason;
    private void submit() {
        name = edtName.getText().toString();
        phone = edtPhone.getText().toString();
        reason = edtReason.getText().toString();
        if(TextUtils.isEmpty(name)){
            ToastUtils.showToast("请输入客户姓名");
            return;
        }
        if(TextUtils.isEmpty(phone)){
            ToastUtils.showToast("请输入客户电话");
            return;
        }
        if(TextUtils.isEmpty(reason)){
            ToastUtils.showToast("请输入推荐理由");
            return;
        }
        doPost();

    }

    private void doPost() {
        PromoteRequestFilter filter =  new PromoteRequestFilter((BaseParentActivity) activity);
        filter.requestBean.type = "2";
        filter.requestBean.phone = phone;
        filter.requestBean.push_msg = reason;
        filter.requestBean.name = name;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<PromoteSucessResponseBean>() {
            @Override
            public void onSuccess(PromoteSucessResponseBean result) {
                if(result.getCode() == 0){
                    ToastUtils.showToast("推单成功");
                    finish();
                }else{
                    ToastUtils.showToast("推单失败，请稍后再试");
                }

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }

    private void chooseContact() {

////        Uri uri = Uri.parse("content://contacts/people");
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setData(android.provider.Contacts.People.CONTENT_URI);
////        Intent intent = new Intent(Intent.ACTION_PICK, uri);
//        startActivityForResult(intent, 0);
        TurnToContactActivity();

    }

    /*
    * 跳转联系人列表的回调函数
    * */

    private void TurnToContactActivity(){
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setData(ContactsContract.Contacts.CONTENT_URI);
//        startActivityForResult(intent,0);
        startActivityForResult(new Intent(this, ActivityContacts.class),300);
    }



    class ReadContactMsg{
        private String name;
        private String phone;
        public ReadContactMsg(Context context, Intent data){
            super();
            Uri contactData = data.getData();
            CursorLoader cursorLoader = new CursorLoader(context,contactData,null,null,null,null);
            Cursor cursor = cursorLoader.loadInBackground();
            if(cursor.moveToFirst()){
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                phone = "此联系人暂未存入号码";
                Cursor phones = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                        null,
                        null);
                if (phones.moveToFirst()) {
                    phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                phones.close();
            }
            cursor.close();
        }

        public String getName() {
            return name;
        }

        public String getPhone() {
            return phone;
        }
    }
//    private String[] getPhoneContacts(Uri uri) {
//        String[] contact=new String[2];
//        //得到ContentResolver对象
//        ContentResolver cr = getContentResolver();
//        //取得电话本中开始一项的光标
//        Cursor cursor=cr.query(uri,null,null,null,null);
//        if(cursor!=null)
//        {
//            cursor.moveToFirst();
//            //取得联系人姓名
//            int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
//            contact[0]=cursor.getString(nameFieldColumnIndex);
//            //取得电话号码
//            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
//                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
//            if(phone != null){
//                phone.moveToFirst();
//                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//            }
//            phone.close();
//            cursor.close();
//        }
//        else
//        {
//            return null;
//        }
//        return contact;
//    }

    private ReadContactMsg readContactMsg;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //获取客户列表
        if(requestCode == REQUEST_CODE){
            if( resultCode == 200 && data != null){
                String phone = data.getStringExtra("phone");
                String name = data.getStringExtra("name");
                edtName.setText(name);
                edtPhone.setText(phone);
            }else{
                return;
            }
        }

        //获取手机通讯录
        if(requestCode == 300){
            if(data!=null){
//                if(resultCode== AppCompatActivity.RESULT_OK){
//                    readContactMsg = new ReadContactMsg(this,data);
//                    edtName.setText(readContactMsg.getName());
//                    edtPhone.setText(readContactMsg.getPhone());
//                }

                edtName.setText(data.getStringExtra("name"));
                edtPhone.setText(data.getStringExtra("number"));
            }
            return;
//                //处理返回的data,获取选择的联系人信息
//                Uri uri=data.getData();
//                String[] contacts = getPhoneContacts(uri);
//                edtName.setText(contacts[0]);
//                if(contacts[1].contains("-")) {
//                    String[] split = contacts[1].split("-");
//                    StringBuffer str = new StringBuffer();
//                    for (int i = 0; i < split.length; i++) {
//                        str.append(split[i].trim());
//                    }
//                    String phones= new String(str);
//                    Log.e(TAG, "onActivityResult: ---"+phones);
//                    edtPhone.setText(phones.replace(" ",""));
//                }else{
//                    edtPhone.setText(contacts[1].replace(" ",""));
//                }
//            }else{
//                return;
//            }
        }
    }
}

